package com.server.servlet;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ServletContext {
	private static Map<String, Servlet> servletMap = new HashMap<>();
	
	static{
		parseServletXml();
	}
	
	public static void parseServletXml(){
		try {
			SAXReader reader = new SAXReader();
			File file = new File("./conf/servlet.xml");
			Document doc = reader.read(file);
			Element ele = doc.getRootElement();
			
			List<Element> list = ele.elements("servlet");
			
			for(Element e : list){
				String path = e.attributeValue("path").trim();
				//反射
				Class cls = Class.forName(e.attributeValue("class"));
				Constructor c = cls.getConstructor();
				Servlet servlet = (Servlet)c.newInstance();
				servletMap.put(path, servlet);
			}
		} catch (DocumentException | ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static Servlet getServlet(String key){
		return servletMap.get(key);
	}
	
	
	public static boolean servletIsExit(String key){
		return servletMap.containsKey(key);
	}
	
	
}
